package org.testis.gui.mvc.view.testdesign;

import org.testis.gui.mvc.view.*;
import org.testis.gui.mvc.controller.testdesign.RunningTestSuiteController;
import org.testis.gui.mvc.controller.TestDesignControllerList;
import org.testis.gui.mvc.utilities.GUIMessageListener;
import org.testis.gui.mvc.utilities.Validatable;
import org.testis.testdriver.AtofEnumaration.ExecutionInterventionType;
import org.testis.utils.AtofDebuggingInputProvider;
import java.awt.Frame;
import java.awt.event.WindowListener;
import java.beans.PropertyChangeEvent;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;

/**
 *
 * @author  Cahit Emir Erel
 */
public class RunningTestSuiteView extends javax.swing.JDialog implements
        AbstractViewPanel, Validatable {

    private static final long serialVersionUID = 2129857L;

    public RunningTestSuiteView(Frame frame,
            boolean modal) {
        super(frame,
                modal);
        initComponents();
        try {
            call.init();
        } catch (Exception ex) {
            ex.printStackTrace();
            System.out.println("CAN NOT LISTEN TO THE JMS MESSAGES!");
        }
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        panel1 = new java.awt.Panel();
        progressBar = new org.testis.gui.mvc.utilities.AtofProgressBar();
        failedDebuggerRadioButton = new javax.swing.JRadioButton();
        debuggerRadioButton = new javax.swing.JRadioButton();
        runnerRadioButton = new javax.swing.JRadioButton();
        startButton = new javax.swing.JButton();
        abortButton = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTextArea1 = new javax.swing.JTextArea();
        btnAbort = new javax.swing.JButton();
        btnRetry = new javax.swing.JButton();
        btnContinue = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
        setTitle("Run Test Suite");
        setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
        setResizable(false);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosed(java.awt.event.WindowEvent evt) {
                formWindowClosed(evt);
            }
            public void windowClosing(java.awt.event.WindowEvent evt) {
                formWindowClosing(evt);
            }
        });

        progressBar.setString("Idle");
        progressBar.setStringPainted(true);

        failedDebuggerRadioButton.setText("Failed Debugger");
        failedDebuggerRadioButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                failedDebuggerRadioButtonActionPerformed(evt);
            }
        });

        debuggerRadioButton.setText("Debugger");
        debuggerRadioButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                debuggerRadioButtonActionPerformed(evt);
            }
        });

        runnerRadioButton.setText("Runner");
        runnerRadioButton.setRolloverEnabled(false);
        runnerRadioButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                runnerRadioButtonActionPerformed(evt);
            }
        });

        startButton.setText("Start");
        startButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                startButtonActionPerformed(evt);
            }
        });

        abortButton.setText("Abort");
        abortButton.setEnabled(false);
        abortButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                abortButtonActionPerformed(evt);
            }
        });

        jTextArea1.setColumns(20);
        jTextArea1.setRows(5);
        jTextArea1.setAlignmentY(BOTTOM_ALIGNMENT);
        jScrollPane1.setViewportView(jTextArea1);

        btnAbort.setText("Abort");
        btnAbort.setEnabled(false);
        btnAbort.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAbortActionPerformed(evt);
            }
        });

        btnRetry.setText("Retry");
        btnRetry.setEnabled(false);
        btnRetry.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnRetryActionPerformed(evt);
            }
        });

        btnContinue.setText("Continue");
        btnContinue.setEnabled(false);
        btnContinue.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnContinueActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout panel1Layout = new javax.swing.GroupLayout(panel1);
        panel1.setLayout(panel1Layout);
        panel1Layout.setHorizontalGroup(
            panel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, panel1Layout.createSequentialGroup()
                .addGroup(panel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(panel1Layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(panel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 749, Short.MAX_VALUE)
                            .addComponent(progressBar, javax.swing.GroupLayout.DEFAULT_SIZE, 749, Short.MAX_VALUE)))
                    .addGroup(panel1Layout.createSequentialGroup()
                        .addGap(190, 190, 190)
                        .addComponent(btnAbort)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnRetry)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnContinue)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 171, Short.MAX_VALUE)
                        .addGroup(panel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                            .addComponent(runnerRadioButton, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(debuggerRadioButton, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(failedDebuggerRadioButton, javax.swing.GroupLayout.Alignment.LEADING))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(panel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                            .addComponent(abortButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(startButton, javax.swing.GroupLayout.DEFAULT_SIZE, 84, Short.MAX_VALUE))))
                .addContainerGap())
        );
        panel1Layout.setVerticalGroup(
            panel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, panel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 220, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(progressBar, javax.swing.GroupLayout.PREFERRED_SIZE, 18, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGroup(panel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, panel1Layout.createSequentialGroup()
                        .addGap(35, 35, 35)
                        .addComponent(startButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(abortButton))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, panel1Layout.createSequentialGroup()
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(failedDebuggerRadioButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(debuggerRadioButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(runnerRadioButton))
                    .addGroup(panel1Layout.createSequentialGroup()
                        .addGap(32, 32, 32)
                        .addGroup(panel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(btnAbort)
                            .addComponent(btnRetry)
                            .addComponent(btnContinue))))
                .addContainerGap())
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(panel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(panel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void formWindowClosed(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosed

        WindowListener[] listeners = this.getWindowListeners();
        for (int i = 0; i < listeners.length; i++) {
            this.removeWindowListener(listeners[i]);
        }
        this.setEnabled(false);
        try {
            call.destroy();
        } catch (Exception ex) {
        }
        TestDesignControllerList.newInstance().getRunningTestSuiteController().
                operationCloseWindow();

    }//GEN-LAST:event_formWindowClosed

    private void failedDebuggerRadioButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_failedDebuggerRadioButtonActionPerformed

        TestDesignControllerList.newInstance().getRunningTestSuiteController().
                operationChangeMode("Failed Debugger");
        failedDebuggerRadioButton.setSelected(true);
        //runnerRadioButton.setSelected(false);
        //debuggerRadioButton.setSelected(false);
        failedDebuggerRadioButton.repaint();
}//GEN-LAST:event_failedDebuggerRadioButtonActionPerformed

    private void runnerRadioButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_runnerRadioButtonActionPerformed

        TestDesignControllerList.newInstance().getRunningTestSuiteController().
                operationChangeMode("Runner");
        //failedDebuggerRadioButton.setSelected(false);
        runnerRadioButton.setSelected(true);
        //debuggerRadioButton.setSelected(false);
        runnerRadioButton.repaint();
    }//GEN-LAST:event_runnerRadioButtonActionPerformed

    private void debuggerRadioButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_debuggerRadioButtonActionPerformed

        TestDesignControllerList.newInstance().getRunningTestSuiteController().
                operationChangeMode("Debugger");
        //failedDebuggerRadioButton.setSelected(false);
        //runnerRadioButton.setSelected(false);
        debuggerRadioButton.setSelected(true);
        debuggerRadioButton.repaint();
    }//GEN-LAST:event_debuggerRadioButtonActionPerformed

    private void abortButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_abortButtonActionPerformed
        if (TestDesignControllerList.newInstance().getRunningTestSuiteController().
                operationAbort()) {
            abortButton.setEnabled(false);
            abortButton.setText("Aborting");
        }
}//GEN-LAST:event_abortButtonActionPerformed
    private GUIMessageListener call = new GUIMessageListener();

    private void startButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_startButtonActionPerformed

        if (startButton.getText().equals("Start")) {
            startButton.setEnabled(false);
            startButton.setText("Starting");
            TestDesignControllerList.newInstance().getRunningTestSuiteController().
                    operationStart(call);

        } else if (startButton.getText().equals("Pause")) {
            if (TestDesignControllerList.newInstance().getRunningTestSuiteController().
                    operationPause()) {
                startButton.setEnabled(false);
                startButton.setText("Pausing");
            }
        } else if (startButton.getText().equals("Resume")) {
            if (TestDesignControllerList.newInstance().getRunningTestSuiteController().
                    operationResume()) {
                startButton.setEnabled(false);
                startButton.setText("Resuming");
            }
        }
        failedDebuggerRadioButton.setEnabled(false);
        runnerRadioButton.setEnabled(false);
        debuggerRadioButton.setEnabled(false);
        failedDebuggerRadioButton.repaint();
        runnerRadioButton.repaint();
        debuggerRadioButton.repaint();
        startButton.repaint();
    }//GEN-LAST:event_startButtonActionPerformed

private void btnAbortActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAbortActionPerformed
    AtofDebuggingInputProvider.getInstance().setInput("A");
    TestDesignControllerList.newInstance().getRunningTestSuiteController().
            operationDebuggingBreak(false);
}//GEN-LAST:event_btnAbortActionPerformed

private void btnRetryActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnRetryActionPerformed
    AtofDebuggingInputProvider.getInstance().setInput("R");
    TestDesignControllerList.newInstance().getRunningTestSuiteController().
            operationDebuggingBreak(false);
}//GEN-LAST:event_btnRetryActionPerformed

private void btnContinueActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnContinueActionPerformed
    AtofDebuggingInputProvider.getInstance().setInput("C");
    TestDesignControllerList.newInstance().//GEN-LAST:event_btnContinueActionPerformed
                getRunningTestSuiteController().operationDebuggingBreak(false);

    }
    private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
        if (!startButton.getText().equals("Start")) {
            int option = JOptionPane.showConfirmDialog(this, "Are you sure?You are about to stop running test...");
            if (option == JOptionPane.OK_OPTION) {
                abortButtonActionPerformed(null);
            }
            return;
        }
        setDefaultCloseOperation(DISPOSE_ON_CLOSE);
        dispose();
   }//GEN-LAST:event_formWindowClosing
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton abortButton;
    private javax.swing.JButton btnAbort;
    private javax.swing.JButton btnContinue;
    private javax.swing.JButton btnRetry;
    private javax.swing.JRadioButton debuggerRadioButton;
    private javax.swing.JRadioButton failedDebuggerRadioButton;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextArea jTextArea1;
    private java.awt.Panel panel1;
    private javax.swing.JProgressBar progressBar;
    private javax.swing.JRadioButton runnerRadioButton;
    private javax.swing.JButton startButton;
    // End of variables declaration//GEN-END:variables

    @Override
    public void modelPropertyChange(PropertyChangeEvent evt) {
        //System.out.println(this.getClass() + " "+evt.getPropertyName());
        if (evt.getPropertyName().equals(
                RunningTestSuiteController.SHOW_RUN_TEST_SUITE)) {
            this.setVisible(true);
        } else if (evt.getPropertyName().equals(
                RunningTestSuiteController.ENABLE_ABORT_BUTTON)) {
            btnAbort.setEnabled((Boolean) evt.getNewValue());
        } else if (evt.getPropertyName().equals(
                RunningTestSuiteController.ENABLE_CONTINUE_BUTTON)) {
            btnContinue.setEnabled((Boolean) evt.getNewValue());
        } else if (evt.getPropertyName().equals(
                RunningTestSuiteController.ENABLE_RETRY_BUTTON)) {
            btnRetry.setEnabled((Boolean) evt.getNewValue());
        } else if (evt.getPropertyName().equals(
                RunningTestSuiteController.CHANGE_STATE)) {
            ExecutionInterventionType val = (ExecutionInterventionType) evt.getNewValue();
            switch (val) {
                case Resume:
                    startButton.setText("Pause");
                    startButton.setEnabled(true);
                    abortButton.setText("Abort");
                    abortButton.setEnabled(true);
                    break;
                case Abort:
                    abortButton.setText("Abort");
                    abortButton.setEnabled(true);
                    break;
                case Pause:
                    startButton.setText("Resume");
                    startButton.setEnabled(true);
                    break;
            }
        } else if (evt.getPropertyName().equals(
                RunningTestSuiteController.CHANGE_MODE)) {
            String mode = (String) evt.getNewValue();
            if (mode.equals("Runner")) {
                runnerRadioButton.setSelected(true);
                debuggerRadioButton.setSelected(false);
                failedDebuggerRadioButton.setSelected(false);
                runnerRadioButton.repaint();
                debuggerRadioButton.repaint();
                failedDebuggerRadioButton.repaint();
            } else if (mode.equals("Debugger")) {
                runnerRadioButton.setSelected(false);
                debuggerRadioButton.setSelected(true);
                failedDebuggerRadioButton.setSelected(false);
                runnerRadioButton.repaint();
                debuggerRadioButton.repaint();
                failedDebuggerRadioButton.repaint();
            } else if (mode.equals("Failed Debugger")) {
                runnerRadioButton.setSelected(false);
                debuggerRadioButton.setSelected(false);
                failedDebuggerRadioButton.setSelected(true);
                runnerRadioButton.repaint();
                debuggerRadioButton.repaint();
                failedDebuggerRadioButton.repaint();
            }
        } else if (evt.getPropertyName().equals(
                RunningTestSuiteController.CHANGE_OUTPUT)) {
            jTextArea1.append(evt.getNewValue().toString() + "\n");
            jScrollPane1.getVerticalScrollBar().setValue(jScrollPane1.getVerticalScrollBar().
                    getMaximum());
        } else if (evt.getPropertyName().equals(
                RunningTestSuiteController.IS_RUNNING)) {
            Boolean isRunning = (Boolean) evt.getNewValue();
            //System.out.println("isRunning=" + isRunning);
            try {
                if (isRunning) {
                    ((org.testis.gui.mvc.utilities.AtofProgressBar) progressBar).setIndeterminate(true);
                    progressBar.setString("Running Test Suite");
                } else {
                    ((org.testis.gui.mvc.utilities.AtofProgressBar) progressBar).setIndeterminate(false);
                    progressBar.setString("Idle");
                }
            } catch (Exception ex) {
            }
            startButton.setText("Pause");
            startButton.setEnabled(true);
            abortButton.setText("Abort");
            abortButton.setEnabled(true);
            failedDebuggerRadioButton.setEnabled(false);
            runnerRadioButton.setEnabled(false);
            debuggerRadioButton.setEnabled(false);
            failedDebuggerRadioButton.repaint();
            runnerRadioButton.repaint();
            debuggerRadioButton.repaint();
            startButton.repaint();
            abortButton.repaint();
            updateProgressBar();

        } else if (evt.getPropertyName().equals(
                RunningTestSuiteController.TEST_END)) {
            startButton.setText("Start");
            abortButton.setEnabled(false);
            abortButton.setText("Abort");
            failedDebuggerRadioButton.setEnabled(true);
            runnerRadioButton.setEnabled(true);
            debuggerRadioButton.setEnabled(true);
            failedDebuggerRadioButton.repaint();
            runnerRadioButton.repaint();
            debuggerRadioButton.repaint();
            abortButton.repaint();
            startButton.repaint();
        }

    }

    private void updateProgressBar() {
        try {
            progressBar.updateUI();
        } catch (RuntimeException ex) {
        } catch (Exception ex) {
        }
    }

    @Override
    public boolean validateForm() {
        boolean valid = true;
//        StringBuilder builder = new StringBuilder();
//        if (ValidationUtils.isEmpty(nameTextField.getText())) {
//            builder.append("Name must not be empty.\n");
//
//            valid = false;
//        }
//        if (!valid) {
//        JOptionPane.showMessageDialog(null,
//                                      builder.toString(),
//                                      "Error",
//                                      JOptionPane.ERROR_MESSAGE);
//        }
        return valid;
    }
}
